package com.atwisdom.star.core.bsl.functionClass;

import com.alibaba.fastjson.JSONObject;
import com.atwisdom.star.common.vo.ActionData;
import com.atwisdom.star.common.vo.JsonResult;
import com.atwisdom.star.common.vo.ResultInfo;
import com.googlecode.aviator.AviatorEvaluator;
import com.googlecode.aviator.Expression;
import com.jayway.jsonpath.JsonPath;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 *
 * @Date: 2023-12-05 09:33
 */
public interface CalculateService {

    /**
     * 按条件查询，并汇总数据
     *
     * @param actionData 参数
     * @return 返回值
     */
    default ResultInfo<?> queryAndCalculate(ActionData<JSONObject> actionData) {
        List<JSONObject> queryJsonList = queryJson(actionData);
        String statisticsExpression = actionData.getStatisticsExpression();
        HashMap<String, Object> calculateParamMap = new HashMap<>();
        Map<String, String> jsonPathMap = actionData.getStatisticsJsonPathMap();
        jsonPathMap.forEach((paramName, jsonPath) -> {
            Object result = JsonPath.read(queryJsonList, jsonPath);
            calculateParamMap.put(paramName, result);
        });
        Expression expression = AviatorEvaluator.compile(statisticsExpression, true);
        Object result = expression.execute(calculateParamMap);
        return JsonResult.success(result);
    }


    List<JSONObject> queryJson(ActionData<JSONObject> actionData);

}
